<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormType } from './index'
import { GetDataDetail, PostCreateData, PutModifyData } from '@/api/modules/givefacialmaskact'
import { GetOptionData } from '@/api/modules/voucher'
import detailStore from '@/store/modules/cacheData'

const router = useRouter()
const route = useRoute()
const detailData = detailStore()

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<FormType>({
  title: '',
  bgColor: '',
  bgImg: '',
  getTicketBtn: '',
  shareBtn: '',
  ticketBaoIcon: '',
  ticketId: '',
  ticketsArray: [],
  processBgColor: '',
  processColor: '',
  taskJson: [],
  getTaskBtn: '',
  noFinishBtn: '',
  finishBtn: '',
  shareTxt: '',
  shareImg: '',
  bottomLogo: '',
  getListIcon: '',
  nogetListIcon: '',
  actStatus: 0,
  qvPic: '',
  ruleBtn: '',
  rulePic: '',
  ticketBaoBg: '',
  descriptionTxt: '',
  descriptionPic: '',
})

interface optionType {
  id: number
  name: string
}
const optionData = ref<optionType[]>([])

const id = route.query.id as string

// 图片上传赋值
function handleUploadSuccess(url: string, key: string, type?: string, subscript?: number, keys?: string) {
  if (type) {
    // eslint-disable-next-line ts/ban-ts-comment
    // @ts-expect-error
    ruleForm.value[key][subscript][keys] = url
  }
  else {
    // eslint-disable-next-line ts/ban-ts-comment
    // @ts-expect-error
    ruleForm.value[key] = url
  }
}

// 提交
async function SubmitData() {
  const params = { ...ruleForm.value }
  if (params.ticketsArray.length !== 12) {
    ElMessage.error('请上传12张图片')
    return
  }
  params.ticketsArray = (params.ticketsArray as string[]).map((item: string) => {
    return `"${item}"`
  })

  params.ticketsArray = `[${(params.ticketsArray as string[]).join(',')}]`
  // params.taskJson = params.taskJson.replace(/"/g, '')

  if (id) {
    // 编辑

    ruleForm.value.id = id
    PutModifyData(params).then((res: any) => {
      if (res.statusCode === 200) {
        ElMessage.success('编辑成功')
        router.push({ name: 'givefacialmaskactIndex' })
      }
    })
  }
  else {
    // 添加
    PostCreateData(params).then((res: any) => {
      if (res.statusCode === 200) {
        ElMessage.success('添加成功')
        detailData.EmptyGivefacialmaskact()
        router.push({ name: 'givefacialmaskactIndex' })
      }
    })
  }
}
interface JsonType {
  ticketId: number
  ticket_img: string
  finish_nums: number
  finish_icon: string
  link_url: string
}
// 奖品添加
function AddCarousel() {
  (ruleForm.value.taskJson as JsonType[]).push({
    ticketId: 0,
    ticket_img: '',
    finish_nums: 0,
    finish_icon: '',
    link_url: '',
  })
}

// 奖品删除
function DeleteCarousel(index: number) {
  ElMessageBox.confirm(
    '你确定要删除这该条吗？',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      (ruleForm.value.taskJson as JsonType[]).splice(index, 1)
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

watch(ruleForm, (newValue) => {
  if (!id) {
    detailData.RememberGivefacialmaskact(newValue)
  }
}, { deep: true })

onMounted(async () => {
  if (id) {
    await GetDataDetail(id).then((res: any) => {
      if (res.statusCode === 200) {
        ruleForm.value = res.data
        ruleForm.value.ticketsArray = JSON.parse((ruleForm.value.ticketsArray as string))
      }
    })
  }
  else {
    ruleForm.value = detailData.GetGivefacialmaskactData()
  }
  await GetOptionData().then((res: any) => {
    if (res.statusCode === 200) {
      optionData.value = res.data
    }
  })
})
</script>

<template>
  <div>
    <PageHeader :title="id ? '编辑' : '添加'" />
    <ElForm ref="ruleFormRef" label-position="top" label-width="80px" :model="ruleForm">
      <PageMain title="基础信息">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="活动主题">
              <el-input v-model="ruleForm.title" style="width: 300px;" placeholder="请输入活动主题" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="试用说明文案">
              <el-input v-model="ruleForm.descriptionTxt" style="width: 300px;" placeholder="请输入试用说明文案" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="分享语">
              <el-input v-model="ruleForm.shareTxt" type="textarea" style="width: 500px;" placeholder="请输入分享语" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="活动状态">
              <el-radio-group v-model="ruleForm.actStatus">
                <el-radio :value="-1">
                  结束
                </el-radio>
                <el-radio :value="0">
                  未开始
                </el-radio>
                <el-radio :value="1">
                  开始
                </el-radio>
              </el-radio-group>
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="背景色">
              <el-color-picker v-model="ruleForm.bgColor" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="进度条背景色">
              <el-color-picker v-model="ruleForm.processBgColor" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="进度条色">
              <el-color-picker v-model="ruleForm.processColor" />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
      <PageMain title="上传图片">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="分享图">
              <ImageUpload
                width="auto" height="200" :size="5" :url="ruleForm.shareImg" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'shareImg')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="企微弹层">
              <ImageUpload
                width="auto" height="200" :size="5" :url="ruleForm.qvPic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'qvPic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="背景图">
              <ImageUpload
                width="auto" height="200" :size="5" :url="ruleForm.bgImg" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'bgImg')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="卡包图标">
              <ImageUpload
                width="auto" height="80" :size="5" :url="ruleForm.ticketBaoIcon" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'ticketBaoIcon')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="领取卡包按钮">
              <ImageUpload
                width="auto" height="80" :size="5" :url="ruleForm.getTicketBtn" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'getTicketBtn')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="邀请卡包按钮">
              <ImageUpload
                width="auto" height="80" :size="5" :url="ruleForm.shareBtn" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'shareBtn')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="领取奖励按钮">
              <ImageUpload
                width="auto" height="80" :size="5" :url="ruleForm.getTaskBtn" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'getTaskBtn')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="未达成按钮">
              <ImageUpload
                width="auto" height="80" :size="5" :url="ruleForm.noFinishBtn" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'noFinishBtn')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="已领取按钮">
              <ImageUpload
                width="auto" height="80" :size="5" :url="ruleForm.finishBtn" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'finishBtn')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="底部logo">
              <ImageUpload
                width="auto" height="100" :size="5" :url="ruleForm.bottomLogo" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'bottomLogo')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="用户已领取按钮">
              <ImageUpload
                width="auto" height="100" :size="5" :url="ruleForm.getListIcon" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'getListIcon')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="用户未领取按钮">
              <ImageUpload
                width="auto" height="100" :size="5" :url="ruleForm.nogetListIcon" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'nogetListIcon')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="规则按钮">
              <ImageUpload
                width="auto" height="100" :size="5" :url="ruleForm.ruleBtn" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'ruleBtn')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="卡包弹窗背景图">
              <ImageUpload
                width="auto" height="100" :size="5" :url="ruleForm.ticketBaoBg" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'ticketBaoBg')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="试用说明图片">
              <ImageUpload
                width="auto" height="100" :size="5" :url="ruleForm.descriptionPic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'descriptionPic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="24">
            <ElFormItem label="规则图">
              <ImageUpload
                width="auto" height="100" :size="5" :url="ruleForm.rulePic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'rulePic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="绑定券">
              <el-select v-model="ruleForm.ticketId" filterable placeholder="请选择">
                <el-option
                  v-for="item in optionData"
                  :key="item.id"
                  :label="`${item.id}-${item.name}`"
                  :value="item.id"
                />
              </el-select>
            </ElFormItem>
          </ElCol>
          <ElCol :md="24">
            <ElFormItem label="12张券图标">
              <ImagesUpload
                :width="200" :height="150" :size="5" :url="(ruleForm.ticketsArray as string[])" :ext="['jpg', 'png']" :max="12"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
      <PageMain title="奖励">
        <div>
          <el-button type="success" class="mb-5" @click="AddCarousel">
            新增
          </el-button>
        </div>
        <ElRow :gutter="20">
          <ElCol v-for="(item, index) in (ruleForm.taskJson as JsonType[])" :key="item.ticketId" :md="8" class="mb-5">
            <el-card shadow="hover">
              <ElFormItem label="去使用链接">
                <el-input v-model="item.link_url" class="max-w-xs" placeholder="请输入去使用链接" />
              </elformitem>
              <ElFormItem label="完成人数">
                <el-input v-model="item.finish_nums" class="max-w-xs" placeholder="请输入完成人数" />
              </elformitem>
              <ElFormItem label="完成人数图标">
                <ImageUpload
                  height="120" width="120" :size="1" :url="item.finish_icon" :ext="['jpg', 'png']"
                  @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'taskJson', 'list', index, 'finish_icon')"
                />
              </ElFormItem>
              <ElFormItem label="绑定优惠券">
                <el-select v-model="item.ticketId" filterable placeholder="请选择">
                  <el-option
                    v-for="items in optionData"
                    :key="items.id"
                    :label="`${items.id}-${items.name}`"
                    :value="items.id"
                  />
                </el-select>
              </ElFormItem>
              <ElFormItem label="券图">
                <ImageUpload
                  height="120" width="120" :size="1" :url="item.ticket_img" :ext="['jpg', 'png']"
                  @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'taskJson', 'list', index, 'ticket_img')"
                />
              </ElFormItem>
              <template #footer>
                <div class="text-right">
                  <el-button type="danger" @click="DeleteCarousel(index)">
                    删除
                  </el-button>
                </div>
              </template>
            </el-card>
          </ElCol>
        </ElRow>
      </PageMain>
    </ElForm>
    <div style="height: 80px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData()">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

<style lang="scss" scoped>
.box {
  .title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
}

.card-box {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;
}
</style>
